//
//  HLOAuthController.m
//  weibo-OC
//
//  Created by 黄力 on 15/12/15.
//  Copyright © 2015年 HLTest. All rights reserved.
//

#import "HLOAuthController.h"
#import "HLUserAccountViewModel.h"
#import "HLUserAccount.h"
#import <SVProgressHUD.h>

@interface HLOAuthController ()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *webView;

@end

@implementation HLOAuthController

- (void)loadView {
    //将控制器替换成webView
    UIWebView *webView = [[UIWebView alloc] init];
    //设置代理
    webView.delegate = self;
    self.webView = webView;
    self.view = webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加左上角关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(clickCloseBtn)];
    //添加右上角自动填充按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"自动填充" style:UIBarButtonItemStylePlain target:self action:@selector(clickAutoBtn)];
    //进行网络请求
    [self loadURLRequest];
}

//点击关闭按钮
- (void)clickCloseBtn {
    //跳转会上个控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}
//点击自动填充按钮
- (void)clickAutoBtn {
    //执行javascript代码
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('userId').value = '15572595921',document.getElementById('passwd').value = 'qwe5237972'"];
}

- (void)loadURLRequest {
    //拼接路径
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",OAuthAppKey,OAuthAppRedirect];
    //请求页面
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
}

#pragma mark - webView代理方法
//将要发送网络请求时调用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    //获取网址
    NSString *urlStr = request.URL.absoluteString;
    //根据网址头来判断是否继续执行请求
    if ([urlStr hasPrefix:@"https://api.weibo.com/oauth2/authorize"]) {
        return YES;
    }
    //如果是授权成功后的跳转的请求就进行拦截
    if ([urlStr hasPrefix:@"https://www.baidu.com/"]) {
        NSLog(@"拦截");
        //获取返回的code
        NSString *code = [request.URL.query substringFromIndex:5];
        //根据code进行网络请求获取token
        [HLUserAccountViewModel loadTokenWithCode:code withFinshBlock:^(BOOL success) {
            //移除加载视图
            [SVProgressHUD dismiss];
            if (success) {
                [self dismissViewControllerAnimated:NO completion:^{
                    //发送通知修改根控制器
                    [[NSNotificationCenter defaultCenter] postNotificationName:MainWindowChangeRootControllerNotification object:nil];
                }];
            }
            
        }];
        return NO;
    }
    return NO;
}


///开始网络请求时调用
- (void)webViewDidStartLoad:(UIWebView *)webView {
    //加载视图
    [SVProgressHUD show];
}

//结束网络请求时调用
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //移除
    [SVProgressHUD dismiss];
}

@end
